<?php

class ViewBase {

  public $data;
  public $layout = "layout";
  public $content_type = "text/html";
  public $charset = "utf-8";
  private $css = array();
  private $js = array();

  public function __construct($template = "default"){
    $this->template = $template;
  }

  public function layout($layout = null){
    $this->layout = $layout;
    return $this;
  }

  public function show(){
    extract((array)$this->data);
    $local = Config::get("base_path").Config::get("modules_dir","modules")."/".Controller::getInstance()->module_name."/templates/".$this->template.".php";
    $global = Config::get("base_path")."/templates/".$this->template.".php";

    ob_start();
    if(file_exists($local)){
      require_once($local);
    } elseif(file_exists($global)) {
      require_once($global);
    } else {
      throw new Exception("Couldn't find template: ".$this->template.".php");
    }
    $output = ob_get_clean();

    if(is_string($this->layout)){
      $layout = new View($this->layout);
      $layout->layout(null);
      $layout->data->contents = $output;
      $layout->show();
    } else {
      Header::set('Content-type: '.$this->content_type.'; charset='.$this->charset);
      Header::send();
      echo $output;
    }

    return $this;
  }

  public function css($stylesheet_file){
    if(!in_array($stylesheet_file, $$this->css)) $this->css[] = $stylesheet_file;
    return $this;
  }

  public function js($script_file){
    if(!in_array($script_file, $$this->js)) $this->js[] = $script_file;
    return $this;
  }

  public function include_css() {
    return "<link href=\"" . implode( "\" rel=\"stylesheet\" type=\"text/css\" />\n<link href=\"", $this->css) . "\" rel=\"stylesheet\" type=\"text/css\" />\n";
  }

  public function include_js() {
    return "<script type=\"text/javascript\" src=\"" . implode( "\"></script>\n<script type=\"text/javascript\" src=\"", $this->js) . "\"></script>\n";
  }
}